# Parser Module Makefile

CC = gcc
CFLAGS = -Wall -g -I..
LDFLAGS = -L../lib
LIBS = -lclexer2 -lcore2 -lcvm2

# Target library name and path
LIB_DIR ?= ../lib
ifeq ($(OS),Windows_NT)
    TARGET = cparser2.dll
    LOCAL_TARGET = cparser2.dll
    LDFLAGS += -shared
else
    UNAME_S := $(shell uname -s)
    ifeq ($(UNAME_S),Darwin)
        TARGET = libcparser2.dylib
        LOCAL_TARGET = libcparser2.dylib
        LDFLAGS += -dynamiclib
    else
        TARGET = libcparser2.so
        LOCAL_TARGET = libcparser2.so
        LDFLAGS += -shared
    endif
endif

# Object files
OBJS = parser.o

# Default target - Build shared library
all: build_dependencies $(LIB_DIR)/$(TARGET) $(LOCAL_TARGET)

# Make sure dependencies are built first in the correct order
build_dependencies:
	$(MAKE) -C ../core all
	$(MAKE) -C ../lexer all
	$(MAKE) -C ../vm all

# 通用编译规则 - 使用模式规则
%.o: %.c
	$(CC) $(CFLAGS) -fPIC -c -o $@ $<

# Link object files into shared library
$(LIB_DIR)/$(TARGET): $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
	@echo "Parser library built successfully: $@"

# Build local copy of the shared library
$(LOCAL_TARGET): $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
	@echo "Parser library built locally: $@"

# Parser test program
parser_test: build_dependencies parser_test.c $(LIB_DIR)/$(TARGET)
	$(CC) $(CFLAGS) -o $@.exe parser_test.c -L$(LIB_DIR) -L. -lcparser2 $(LIBS)
	@echo "Parser test program built: $@.exe"

# 四元式生成测试程序
quadruple_test: build_dependencies parser_for_quadruples.o quadruples_test.c
	$(CC) $(CFLAGS) -o $@.exe quadruples_test.c parser_for_quadruples.o -L$(LIB_DIR) -L. $(LIBS)
	@echo "Quadruples test program built: $@.exe"

# 指令打印测试程序
print_instruction_test: build_dependencies print_instruction.o print_instruction_interface.c
	$(CC) $(CFLAGS) -o $@.exe print_instruction_interface.c print_instruction.o -L$(LIB_DIR) -L. $(LIBS)
	@echo "Print instruction test program built: $@.exe"

print_symbol_test: build_dependencies parser.o print_symbol.o
	$(CC) $(CFLAGS) -o $@.exe parser.o print_symbol.o -L$(LIB_DIR) -L. $(LIBS)
	@echo "Print symbol test program built: $@.exe"

# Clean target
clean:
	rm -f $(OBJS) parser_for_quadruples.o print_instruction.o print_symbol.o $(LIB_DIR)/$(TARGET) $(LOCAL_TARGET) parser_test.exe quadruple_test.exe print_instruction_test.exe print_symbol_test.exe


# Help
help:
	@echo "Parser Module Makefile"
	@echo "Available targets:"
	@echo "  all         - Build parser library (default)"
	@echo "  parser_test - Build parser test program"
	@echo "  quadruples_test - Build quadruples generation test program"
	@echo "  print_instruction_test - Build print instruction test program"
	@echo "  print_symbol_test - Build print symbol test program"
	@echo "  clean       - Remove generated files"
	@echo "  help        - Display this help information"

.PHONY: all clean help build_dependencies parser_test quadruples_test print_instruction_test print_symbol_test
